package wms.api.modules.user.controller;

import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import wms.api.core.bean.*;
import wms.api.core.cache.CacheFacade;
import wms.api.core.cache.constants.StatusCode;
import wms.api.core.token.utils.TokenUtils;
import wms.api.core.utils.ContextUtils;
import wms.api.modules.user.domain.LoginUserBean;
import wms.api.modules.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param loginBean
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity login(@Validated @RequestBody LoginUserBean loginBean) {

        int terminal = ContextUtils.getCurAuth().getTerminal();

        if (terminal == 0) {
            return new ResponseErrorEntity(StatusCode.VALIDATION_FAILED, HttpStatus.BAD_REQUEST);
        }

        return userService.login(loginBean);
    }
    @LoginAnnot
    @PostMapping("/logout")
    public ResponseEntity logout()
    {
        AuthEntity curAuth = ContextUtils.getCurAuth();

        CacheFacade.delete(curAuth.getUserId()+ TokenUtils.getSuffix(curAuth.getTerminal()));

        return new ResponseSuccessEntity(StatusCode.LOGIN_OUT_SUCCESS,HttpStatus.OK);
    }
}
